package service;

import dao.UserDao;

import java.util.*;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.testng.annotations.BeforeClass;
import po.User;
import redis.clients.jedis.Jedis;
import utils.FlushUuid;
import utils.ServerResponse;

/**
 * Create by IntelliJ IDEA
 *
 * @author: jsonor
 * @date-Time: 2018/3/26 14:12
 * @description:
 */
@Service
public class Impl implements UserService {

    public static Jedis jedis;
    @Autowired
    private UserDao userDao;
    @Autowired
    private FlushUuid flushUuid;


  @BeforeClass
  public static void init()
  {
    jedis=new Jedis();
  }

    @Override
    public ServerResponse<User> login(String username, String password) {
        int count = userDao.userNameCount(username);
        if (count != 1) {
            return ServerResponse.createError("user do not exist");
        }

        // Todo. password 需要加密
        User user = userDao.findByUserNameAndPassword(username, password);
        if (user == null) {
            return ServerResponse.createError("password error");
        }

        user.setPassword(null);
        user.setQuestion(null);
        user.setAnswer(null);
        return ServerResponse.createSuccess(user);
    }


    @Override
    public ServerResponse insert(User user) throws Exception {
        List<User> list = userDao.findAll();
        user.setCreate_time(new Date());
        user.setUpdate_time(new Date());
        for (User u :
                list) {
            if (user.getUsername().equals(u.getUsername())) {
                return ServerResponse.createError("用户已存在");
            }
        }
        int num= userDao.insert(user);
        Impl.init();
        jedis.sadd("username",user.getUsername());
        //jedis.sadd("email",user.getEmail());
        return ServerResponse.createSuccess("校验成功");
    }

    @Override
    public ServerResponse<User> check(String username, String password) {
        User user = userDao.findByUserNameAndPassword(username, password);
        if (user == null) {
            return ServerResponse.createError("用户未登录,无法获取当前用户信息");
        }
        return ServerResponse.createSuccess(user);
    }

    @Override
    public ServerResponse<User> findByUsername(String username) {
        User user = userDao.findByUsername(username);
        if (user.getQuestion() == null) {
            return ServerResponse.createError("该用户未设置找回密码问题");
        }
        User user1 = new User();
        user1.setQuestion(user.getQuestion());
        return ServerResponse.createSuccess(user1);
    }

    @Override
    public ServerResponse removeSession(HttpSession session) {
        if (session != null) {
            session.removeAttribute("data");
            return ServerResponse.createSuccess("退出成功");
        }
        return ServerResponse.createError("1", "服务端异常");
    }

    @Override
    public ServerResponse get_information(HttpSession session) {
        User user = new User();
        if (session == null) {
            return ServerResponse.createError(10, "用户未登录,无法获取当前用户信息,status=10,强制登录");
        }
        user.setId(1);
        user.setUsername("admin");
        user.setPassword("");
        user.setEmail("admin@163.com");
        user.setPhone("13800138000");
        user.setQuestion("question");
        user.setAnswer("answer");
        user.setRole(1);
        user.setCreate_time(new Date());
        user.setUpdate_time(new Date());
        return ServerResponse.createSuccess(user);
    }

    @Override
    public ServerResponse reset_password(String passwordOld, String passwordNew, HttpSession session) {
        if (session != null) {
            int num = userDao.resetPassword(passwordOld, passwordNew);
            if (num == 0) {
                return ServerResponse.createError("旧密码输入错误");
            }
            return ServerResponse.createSuccess("修改密码成功!");
        }
        return ServerResponse.createSuccess(session);
    }

    @Override
    public ServerResponse update_information(String username, String email, String phone, String question, String answer, HttpSession session) {
        if (session != null) {
            int num = userDao.update_information(username, email, phone, question, answer);
            if (num == 1) {
                return ServerResponse.createSuccess("更新个人信息成功");
            }
        }
        return ServerResponse.createError("用户未登录");
    }

    @Override
    public ServerResponse forget_check_answer(String username, String question, String answer) {
        User byUsername = userDao.findByUsername(username);
        if (!byUsername.getAnswer().equals(answer)||!byUsername.getQuestion().equals(question)) {
            return ServerResponse.createError("问题答案错误");
        }

        return ServerResponse.createSuccess(byUsername);
    }

    @Override
    public ServerResponse check_valid(String str, String type) {
      Impl.init();
      if (jedis.exists(type)) {
        if (jedis.sismember(type, str)) {
          return ServerResponse.createError("用户已存在");
        } else {
          List<User> list = userDao.findAll();
          for (User user : list) {
            if (type.equals("username") && str.equals(user.getUsername())) {
              jedis.sadd("username", str);
              return ServerResponse.createError("用户已存在");
            }
            if (type.equals("email") && str.equals(user.getEmail())) {
              jedis.sadd("email", str);
              return ServerResponse.createError("用户已存在");
            }
          }
        }
      }
      return ServerResponse.createSuccess("校验成功！");
    }
    //@Override
    //public ServerResponse check_valid(String str, String type) {
    //  List<User> list = userDao.findAll();
    //  for (User u :
    //      list) {
    //    if (type.equals("username") && str.equals(u.getUsername())) {
    //      return ServerResponse.createError("用户已存在");
    //    }
    //    if (type.equals("email") && str.equals(u.getEmail())) {
    //      return ServerResponse.createError("用户已存在");
    //    }
    //  }
    //  return ServerResponse.createSuccess("校验成功");
    //}

    @Override
    public ServerResponse<User> forget_reset_password(String username, String passwordNew, String forgetToken) {
        String token = flushUuid.timeOut();
        if (token.equals(forgetToken)) {
            int num = userDao.setPasswordByUserName(username, passwordNew);
            return ServerResponse.createSuccess("修改密码成功！");
        }
        return ServerResponse.createError("修改密码操作失效");
    }
}

